package com.txzt.gaea.STaward.service.impl;

import com.txzt.base.constant.RtnConstant;
import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.STaward.dto.STAwardDTO;
import com.txzt.gaea.STaward.model.STAward;
import com.txzt.gaea.STaward.service.STAwardService;
import com.txzt.gaea.STaward.vo.STAwardVo;
import com.txzt.gaea.api.client.AdminUserRemoteService;
import com.txzt.gaea.base.service.DataPermissionService;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.core.base.context.AdminUserContext;
import com.txzt.gaea.common.enums.FlowFlagEnum;
import com.txzt.gaea.common.enums.IsDeleteEnum;
import com.txzt.gaea.common.enums.STAwardStatusEnum;
import com.txzt.gaea.common.page.PageInfoBT;
import com.txzt.gaea.dto.UserSingleDetailQueryDTO;
import com.txzt.gaea.flow.service.FlowService;
import com.txzt.gaea.flow.vo.FlowBizStepVo;
import com.txzt.gaea.vo.AdminUserVO;
import lombok.extern.log4j.Log4j2;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

@Log4j2
@Service
public class STAwardServiceImpl extends BaseServiceImpl<STAward> implements STAwardService {

    @Autowired
    private AdminUserRemoteService adminUserRemoteService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private DataPermissionService dataPermissionService;

    @Override
    public RtnInfo<PageInfoBT<STAwardVo>> pageList(STAwardDTO stAwardDTO){
        //查询当前用户的查询权限
        dataPermissionService.getCurrentUserPermissionType(stAwardDTO);
        PageQuery<STAwardVo> pageQuery = new PageQuery<>(stAwardDTO.getOffset(),
                stAwardDTO.getLimit(), stAwardDTO);
        PageQuery<STAwardVo> result =
                this.sqlManager.pageQuery("STAward.selectPageList", STAwardVo.class, pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT<>(result));
        }
        UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
        result.getList().forEach(item -> {
            userSingleDetailQueryDTO.setUserId(item.getCreateBy());
            item.setCreateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            userSingleDetailQueryDTO.setUserId(item.getUpdateBy());
            item.setUpdateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            userSingleDetailQueryDTO.setUserId(item.getAwardBy());
            item.setAwardName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
        });
        PageInfoBT<STAwardVo> re = new PageInfoBT<>(result);
        rebuild(re);
        return RtnInfo.success(re);
    }

    private void rebuild(PageInfoBT<STAwardVo> re){
        List<STAwardVo> list = re.getRows();
        if(CollectionUtils.isEmpty(list)){
            re.setTotal(0);
            return;
        }
//        re.setTotal(list.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(STAward stAward){
        stAward.setAwardStatus(STAwardStatusEnum.INIT.getCode());
        return this.sqlManager.insert(stAward);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(STAward stAward){
        return this.sqlManager.updateTemplateById(stAward);
    }

    @Override
    public boolean addCheck(STAward stAward){
        LambdaQuery<STAward> query = sqlManager.lambdaQuery(STAward.class);
        List<STAward> orgList = query.andEq(STAward::getProjectName,stAward.getProjectName())
                .orEq(STAward::getAwardNo,stAward.getAwardNo())
                .orEq(STAward::getCertNo,stAward.getCertNo())
                .andEq(STAward::getIsDelete,IsDeleteEnum.NOTDELETE.getCode())
                .select();
        return 0 >= orgList.size();
    }

    @Override
    public boolean updateCheck(STAward stAward){
        LambdaQuery<STAward> query = sqlManager.lambdaQuery(STAward.class);
        List<STAward> orgList = query.andNotEq(STAward::getId,stAward.getId())
                .and(query.condition()
                        .andEq(STAward::getProjectName,stAward.getProjectName())
                        .orEq(STAward::getAwardNo,stAward.getAwardNo())
                        .orEq(STAward::getCertNo,stAward.getCertNo()))
                .andEq(STAward::getIsDelete,IsDeleteEnum.NOTDELETE.getCode()).select();
        return 0 >= orgList.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id){
        STAward stAward = new STAward();
        stAward.setId(id);
        stAward.setIsDelete(IsDeleteEnum.DELETE.getCode());
        return this.sqlManager.updateTemplateById(stAward);
    }

    @Override
    public RtnInfo<STAward> getInfo(Long id){
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        STAward stAward = this.selectById(id);
        if (null == stAward){
            return RtnInfo.error(RtnConstant.Code.PARAMS_REEOR,"未查到相关信息，请检查上送数据是否正确");
        } else {
            if (stAward.getAwardStatus().equals(STAwardStatusEnum.CHECK.getCode())){
                //获取流程信息
                List<FlowBizStepVo> stepList =
                        flowService.getFlowBizStep(id,FlowFlagEnum.ACHIEVEMENT_MANAGEMENT.getCode());
                stAward.setCheck(false);
                for (FlowBizStepVo flowBizStepVo : stepList){
                    if (null == flowBizStepVo.getStepStatus()){
                        String[] split = adminUserVO.getRoleid().split(",");
                        List<String> list = Arrays.asList(split);
                        boolean hasOne = list.contains(flowBizStepVo.getStepMember());
                        if (hasOne){
                            stAward.setCheck(true);
                            break;
                        }else {
                            break;
                        }
                    }
                }
                stAward.setFlowStep(stepList);
            }
            return RtnInfo.success(stAward);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean gotoCheck(Long id){
        STAward stAward = this.selectById(id);
        stAward.setAwardStatus(STAwardStatusEnum.CHECK.getCode());
        int updateNum = this.sqlManager.updateTemplateById(stAward);
        if (0 == updateNum){
            return false;
        }
        // Todo 开启审批流程 待完成
        flowService.startFlow(id,"tb_st_award","award_status",
                STAwardStatusEnum.BACK.getCode(),STAwardStatusEnum.PASS.getCode(),
                FlowFlagEnum.ACHIEVEMENT_MANAGEMENT.getCode());
        return true;
    }
}
